import {
  apiInterceptors,
  delAuth,
  getAuthPage
} from '@/client/api';
import BlurredCard, { ChatButton, InnerDropdown } from '@/new-components/common/blurredCard';
import System from '@/new-components/layout/System';
import { IAuth } from '@/types/authority';
import { BulbOutlined, DingdingOutlined, PlusOutlined, SearchOutlined, WarningOutlined } from '@ant-design/icons';
import { useDebounceFn, useRequest } from 'ahooks';
import { App, Button, Input, Modal, Pagination, Popover, Segmented, SegmentedProps, Select, Spin, Tag } from 'antd';
import copy from 'copy-to-clipboard';
import moment from 'moment';
import { useRouter } from 'next/router';
import { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import CreateAuthModal from './create-auth-modal/index';

type ModalType = 'edit' | 'add';

export default function AuthContent() {
  const router = useRouter();
  const { t } = useTranslation();
  const { message } = App.useApp();

  const [open, setOpen] = useState<boolean>(false);
  const [spinning, setSpinning] = useState<boolean>(false);
  const [auths, setAuths] = useState<IAuth[]>([]);
  const [currentAuth, setAuthInfo] = useState({});
  const [modalType, setModalType] = useState<ModalType>('add');
  const [filterValue, setFilterValue] = useState('');

  // 分页信息
  const totalRef = useRef<{
    current_page: number;
    total_count: number;
    total_page: number;
  }>();

  const handleCreate = (data) => {
  
    if(data.id){
      setAuthInfo(data)
      setModalType('edit');
    }else{
      setAuthInfo({})
      setModalType('add');
    }
    
    setOpen(true);
  };


  const getListFiltered = useCallback(() => {
    initData({ keyword: filterValue });
  }, [filterValue]);

  const initData = useDebounceFn(
    async params => {
      setSpinning(true);
      const obj: any = {
        ...params
      };
      const [error, data] = await apiInterceptors(getAuthPage(obj));
      if (error) {
        setSpinning(false);
        return;
      }
      if (!data) return;
      setAuths(data?.items || []);
      totalRef.current = {
        current_page: data?.current_page || 1,
        total_count: data?.total_count || 0,
        total_page: data?.total_page || 0,
      };
      setSpinning(false);
    },
    {
      wait: 500,
    },
  ).run;

  const showDeleteConfirm = (auth: IAuth) => {
    Modal.confirm({
      title: t('Tips'),
      icon: <WarningOutlined />,
      content: t('want_delete'),
      okText: t('verify'),
      okType: 'danger',
      cancelText: t('cancel'),
      async onOk() {
        await apiInterceptors(delAuth({ id: auth.id }));
        getListFiltered();
      },
    });
  };

  const onSearch = async (e: any) => {
    const v = e.target.value;
    setFilterValue(v);
  };

  useEffect(() => {
    getListFiltered();
  }, [getListFiltered]);


  return (
    <System>
      <Spin spinning={spinning}>
        <div className='h-screen w-full p-4 md:p-6 overflow-y-auto'>
          <div className='flex justify-between items-center mb-6'>
            <div className='flex items-center gap-4'>
              <Input
                variant='filled'
                value={filterValue}
                prefix={<SearchOutlined />}
                placeholder={t('please_enter_the_keywords')}
                onChange={onSearch}
                onPressEnter={onSearch}
                allowClear
                className='w-[230px] h-[40px] border-1 border-white backdrop-filter backdrop-blur-lg bg-white bg-opacity-30 dark:border-[#6f7f95] dark:bg-[#6f7f95] dark:bg-opacity-60'
              />
            </div>

            <Button
              className='border-none text-white bg-button-gradient flex items-center'
              icon={<PlusOutlined className='text-base' />}
              onClick={(handleCreate)}
            >
              {t('create_auth')}
            </Button>
          </div>
          <div className=' w-full flex flex-wrap pb-12 mx-[-8px]'>
            {auths.map(item => {
              return (
                <BlurredCard
                  key={item.id}
                  code={item.id}
                  name={item.name}
                  description={item.desc}
                  RightTop={
                    <div className='flex items-center gap-2'>
                      <InnerDropdown
                        menu={{
                          items: item.built_in ? [
                            {
                              key: 'edit',
                              label: (
                                <span
                                  onClick={e => {
                                    e.stopPropagation();
                                    handleCreate(item);
                                  }}
                                >
                                  {t('Edit')}
                                </span>
                              ),
                            }
                          ]: [
                            {
                              key: 'edit',
                              label: (
                                <span
                                  onClick={e => {
                                    e.stopPropagation();
                                    handleCreate(item);
                                  }}
                                >
                                  {t('Edit')}
                                </span>
                              ),
                            },
                            {
                              key: 'del',
                              label: (
                                <span
                                  className='text-red-400'
                                  onClick={e => {
                                    e.stopPropagation();
                                    showDeleteConfirm(item);
                                  }}
                                >
                                  {t('Delete')}
                                </span>
                              ),
                            },
                          ],
                        }}
                      />
                    </div>
                  }
                  Tags={
                    <div>
                       { item.built_in && <Tag color="red">{t('auth_built_in')}</Tag> }
                       { item.app_set != -1 && <Tag color="purple">{t('app_label')}</Tag> }
                       {/* { item.knowledge_set != -1  && <Tag color="geekblue">{t('Knowledge_Space')}</Tag> }
                       { item.connect_set!= -1  && <Tag color="green">{t('Database')}</Tag> }
                       { item.flow_set!= -1  && <Tag color="volcano">{t('awel_flow')}</Tag> } */}
                    </div>
                  }
                  rightTopHover={false}
                  LeftBottom={
                    <div className='flex gap-2 text-[#828282]'>
                      {/* <span>{item.owner_name}</span> */}
                      <span>•</span>
                      {item?.update_datetime && <span>{moment(item?.update_datetime).fromNow() + ' ' + t('update')}</span>}
                    </div>
                  }
                  scene=""
                  logo={item?.built_in? "/pictures/admin.png" :"/pictures/ordinary.png"}
                />
              );
            })}
            <div className='w-full flex justify-end shrink-0 pb-12'>
              <Pagination
                total={totalRef.current?.total_count || 0}
                pageSize={12}
                current={totalRef.current?.current_page}
                onChange={async (page, _page_size) => {
                  await initData({ page });
                }}
              />
            </div>
          </div>

          {open && (
            <CreateAuthModal
              open={open}
              onCancel={() => {
                setOpen(false);
              }}
              refresh={initData}
              type={modalType}
              authInfo={currentAuth}
            />
          )}
        </div>
      </Spin>
    </System>
  );
}


